package com.apes.scm.masterdata.product.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.util.JpaUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.product.repository.ProductUomRepository;
import com.apes.scm.masterdata.product.service.ServeCategoryService;
import lombok.Getter;
import lombok.Setter;
import org.dozer.Mapping;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.hibernate.proxy.HibernateProxy;

import javax.persistence.*;
import java.util.List;

/**
 * 功能：商品
 *
 * @author xul
 * @create 2018-01-24 16:00
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = Product.CONST_TABLE_NAME, indexes = {
        @Index(columnList = "name")})
public class Product extends Model {
    public static final String CONST_TABLE_NAME = "mas_product";

    @Id
    @Column(name = "id", length = 10)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "商品编码", padding = 10)
    @Comment("商品编码")
    private String id; //商品编码

    @Column(name = "NAME", nullable = false, length = 100)
    @Comment("商品名称")
    private String name; //商品名称

    @Column(name = "DESCRIPTION", length = 500)
    @Comment("说明")
    private String description; //说明

    @Column(name = "valid")
    @Comment("有效标记")
    private boolean valid = true; //有效

    @Column(name = "BARCODE", length = 60)
    @Comment("条码")
    private String barcode; //条码

    @Name
    @ManyToOne
    @JoinColumn(name = "product_group_id", referencedColumnName = "id")
    @Comment("商品组")
    private ProductGroup productGroup;  //商品组

    @Name
    @ManyToOne
    @JoinColumn(name = "classify_id", referencedColumnName = "id")
    @Comment("商品分类")
    private Classify classify;  //商品分类

    @ManyToOne
    @JoinColumn(name = "category_id", referencedColumnName = "id")
    @Comment("商品类目")
    private Category category;  //商品类目 /配件名称

    @ManyToOne
    @JoinColumn(name = "brand_id", referencedColumnName = "id")
    @Comment("品牌")
    private Brand brand;  //品牌

    @ManyToOne
    @JoinColumn(name = "product_uom_id", referencedColumnName = "id", nullable = false)
    @Comment("计量单位")
    private ProductUom uom; //计量单位

//    @Column(name = "COST_METHOD", length = 30)
//    private String costMethod; //成本方法

    @Transient
//    @Column(name = "type", length = 30)
    @Comment("商品类型")
    private String type; //商品类型：('aut'：服务)，('product'：可库存)

    @Transient
    public String getType() {
        /** 商品类型：('aut'：不可库存)，('product'：可库存) **/
        if (productGroup == null) return "product";
        if (productGroup.isQtyMgmt()) return "product";
        return "aut";
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "tax_id", referencedColumnName = "id")
    @Comment("销项税率")
    private Tax tax; //销项税率

    @Column(name = "specifications", length = 200)
    @Comment("规格")
    private String specifications; // 规格

    @Column(name = "model", length = 200)
    @Comment("型号")
    private String model;  //型号

    private String speAndModel;

    public String getSpeAndModel() {
        if (this.specifications != null && this.model != null) {
            return this.specifications + "/" + this.model;
        } else if (this.specifications != null) {
            return this.specifications + "/";
        } else if (this.model != null) {
            return "/" + this.model;
        } else {
            return "";
        }
    }


    @Column(name = "origin_place", length = 100)
    @Comment("产地")
    private String originPlace;  //产地

    @Column(name = "colour", length = 100)
    @Comment("颜色")
    private String colour;  //颜色

    @Column(name = "stack_level", nullable = false, columnDefinition = "number(8,0) default 0")
    @Comment("堆码层级")
    private int stackLevel = 0;  //堆码层级

    @Column(name = "quality_guarantee_period", nullable = false, columnDefinition = "number(8,0) default 0")
    @Comment("保质期(天)")
    private int qualityGuaranteePeriod = 0;//保质期(天)

    @Column(name = "orgin_id", length = 30)
    @Comment("外部编码")
    private String orginID;

    @Column(name = "free_supplies_valid", columnDefinition = "number(1,0)")
    @Comment("免费耗材标记")
    private boolean freeSuppliesValid = true;

    @Column(name = "free_service_valid", columnDefinition = "number(1,0)")
    @Comment("快速服务标记")
    private boolean freeServiceValid = true;


    @Column(name = "inquiry_valid", columnDefinition = "number(1,0)")
    @Comment("询价需图片标记")
    private Integer inquiryValid = 0;//默认不需要

    public Boolean getInquiryValid(){
        if (inquiryValid==null){
            return false;
        }
        return inquiryValid == 1;
    }
    public void setInquiryValid(Boolean inquiryValid){
        if (inquiryValid==null||!inquiryValid){
            this.inquiryValid=0;
        }else {
            this.inquiryValid=1;
        }
    }

    @Column(name = "worker_valid", columnDefinition = "number(1,0)")
    @Comment("施工标记")
    private Integer workerValid = 1;//默认施工

    public Boolean getWorkerValid(){
        return workerValid == null || workerValid == 1;


    }
    public void setWorkerValid(Boolean workerValid){
        if (workerValid==null||workerValid){
            this.workerValid=1;
        }else {
            this.workerValid=0;
        }
    }




    @Column(name = "oem_id", length = 2000)
    @Comment("oem码")
    private String oemId;

    @Column(name = "instruction", length = 300)
    @Comment("包装说明")
    private String instruction;

    @Column(name = "state", length = 10)
    @Comment("状态")
    private String state; //0:正常 2：停产下市 3.停用 5：预上市


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "custom_marker", referencedColumnName = "id")
    @Comment("自定义标记")
    private Enumeration customMarker;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "fa_category_id", referencedColumnName = "id")
    @Comment("资产类别")
    private FaCategory faCategory;


    public Integer getStar() {
        if (classify!=null&&classify.getId().startsWith("M0103"))return null;
        return star;
    }

    @Transient
    public Integer star = 0;

    @Transient
    public ServeType serveType;

    public ServeType getServeType() {
        ServeCategory serveCategory = SpringManager.getBean(ServeCategoryService.class).findByClassify(this.getClassify());
        if (serveCategory == null) return null;
        if (serveCategory.getServeType() == null) return null;
        serveType = (ServeType) JpaUtil.getImplementation(serveCategory.getServeType());
        serveType = MapUtil.getO(MapUtil.mapped(serveType), ServeType.class);
        return serveType;
    }

    /***
     * 获取商品服务类型
     */
    public ServeType queryServeType() {
        ServeCategory serveCategory = SpringManager.getBean(ServeCategoryService.class).findByClassify(this.getClassify());

        if (serveCategory == null)
            throw new RuntimeException("当前商品所属的商品分类未定义具体的服务类型，商品分类：" + "【" + this.getClassify().getId() + "】" + this.getClassify().getName());
        return serveCategory.getServeType();

    }

    /***
     * 获取转储默认单位
     */
    public List<ProductUom> queryTransferFirstUom() {
        List uoms;
        uoms = SpringManager.getBean(ProductUomRepository.class).findAll(
                JpaDsl.toCriteriaByEq(
                        "uomCategory.id", uom.getUomCategory().getId(),
                        "transferFirst", true
                )
        );
        // 如果不存在默认返回当前商品的单位
        if (uoms.size() == 0) uoms.add(uom);
        return uoms;
    }
}
